package com.lych.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.lych.model.mongo.RecommendUser;
import com.lych.model.mongo.UserLike;
import com.lych.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    /**
     * 查询今日佳人
     */
    public RecommendUser todayBest(Long toUserId) {
        //构建Criteria
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //构建Query对象
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score")))
                .limit(1);
        //调用mongoTemplate查询
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    /**
     * 查询分页
     * @param page
     * @param pagesize
     * @param toUserId
     * @return
     */
    @Override
    public PageResult queryRecommendUser(Integer page, Integer pagesize, Long toUserId) {
        //创建Criteria对象
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //创建Query对象
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        //调用mongoTemplate
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);
        long count = mongoTemplate.count(query, RecommendUser.class);
        return new PageResult(page,pagesize, (int) count,recommendUsers);
    }

    /**
     * 根据佳人id与操作人id查询两者的推荐数据
     * @param userId 佳人id
     * @param toUserId 操作人id
     * @return
     */
    @Override
    public RecommendUser queryById(Long userId, Long toUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("toUserId").is(toUserId));
        RecommendUser user = mongoTemplate.findOne(query, RecommendUser.class);
        if (user == null) {
            user = new RecommendUser();
            user.setUserId(userId);
            user.setToUserId(toUserId);
            user.setScore(95d); //构造缘分值
        }
        return user;
    }

    /**
     * 调用api查询数据（排除喜欢/不喜欢，控制数量）
     * @param userId
     * @param i
     * @return
     */
    @Override
    public List<RecommendUser> queryCardsList(Long userId, int i) {
        //查询喜欢或不喜欢的用户id
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        List<Long> likeUserIds = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        //构造推荐用户的条件
        Criteria criteria = Criteria.where("toUserId").is(userId).and("userId").nin(likeUserIds);
        //使用统计函数，随机获取推荐的用户列表
        TypedAggregation<RecommendUser> recommendUserTypedAggregation = TypedAggregation.newAggregation(RecommendUser.class,
                Aggregation.match(criteria),
                Aggregation.sample(i));
        AggregationResults<RecommendUser> aggregate = mongoTemplate.aggregate(recommendUserTypedAggregation, RecommendUser.class);
        return aggregate.getMappedResults();
    }
}
